package org.example.controller;

import com.huaweicloud.sdk.cbs.v1.CbsClient;
import com.huaweicloud.sdk.cbs.v1.model.ExecuteQaChatRequest;
import com.huaweicloud.sdk.cbs.v1.model.ExecuteQaChatResponse;
import com.huaweicloud.sdk.cbs.v1.model.PostRequestsReq;
import com.huaweicloud.sdk.cbs.v1.region.CbsRegion;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.utils.StringUtils;
import org.example.Entity.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 华为云SDKAPI
 */
@Validated
@RestController
@RequestMapping("/api/sdk")
public class SDKController {

    /**
     * 对话机器人服务
     * @param paramStr
     * @return
     */
    @PostMapping("/chat")
    public Result<Map<String ,String>> list(@RequestBody String paramStr){
        Map<String ,String> map = new HashMap<String ,String>();
        if(StringUtils.isEmpty(paramStr)){
            map.put("answer","请求内容为空");
            return Result.success("error",map);
        }
        // 使用默认配置
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        // 默认连接超时时间为60秒，可根据需要调整
        config.withTimeout(60);
        //配置AK、SK、project_id信息。华为云通过AK识别用户的身份，通过SK对请求数据进行签名验证，用于确保请求的机密性、完整性和请求者身份的正确性。
        String ak = System.getenv("HUAWEICLOUD_SDK_AK");
        String sk = System.getenv("HUAWEICLOUD_SDK_SK");
        String projectId =System.getenv("HUAWEICLOUD_PROJECT_ID");
        String qabotId =System.getenv("HUAWEICLOUD_QABOT_ID");
        BasicCredentials basicCredentials = new BasicCredentials()
                .withAk(ak)
                .withSk(sk)
                .withProjectId(projectId);
        // 初始化指定云服务的客户端 {Service}Client ，以初始化 Region 级服务CBS的 CbsClient 为例
        CbsClient client = CbsClient.newBuilder()
                .withHttpConfig(config)
                .withCredential(basicCredentials)
                .withRegion(CbsRegion.valueOf("cn-north-4"))
                .build();
        // 以调用问答机器人会话接口ExecuteQaChat为例
        ExecuteQaChatRequest request = new ExecuteQaChatRequest();
        // qabot_id获取方法参考本章节“准备工作”
        request.withQabotId(qabotId);
        PostRequestsReq body = new PostRequestsReq();
        // session_id首轮不需要传入或可传入任意值，第二轮开始使用上一轮返回的session_id
        body.withQuestion(paramStr);
        request.withBody(body);
        String answer = "暂时无法回答你的问题";
        try {
            ExecuteQaChatResponse response = client.executeQaChat(request);
            //问答型机器人回复
            if (response.getReplyType() == 0) {
                answer = response.getQabotAnswers().getAnswers().get(0).getAnswer();
            } else if (response.getReplyType() == 1){//任务型机器人回复
                answer = response.getTaskbotAnswers().getAnswer();
            }else if(response.getReplyType() == 1) {//闲聊机器人回复
                answer = response.getChatAnswers().getAnswer();
            }else {
                answer = "暂时无法回答你的问题";
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }

        if(!StringUtils.isEmpty(answer)){
            answer = answer.replace("<p>","").replace("</p>","");
        }
        map.put("answer",answer);
        //3.返回结果
        return Result.success("ok",map);
    }

}
